package com.ltsznh.android.bluecompass;

import android.app.Activity;
import android.graphics.Color;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdSize;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.mediation.admob.AdMobExtras;

import java.text.SimpleDateFormat;


public class MainActivity extends Activity implements SensorEventListener {
    private SensorManager cSensorManager;

    private Sensor orientationSensor;
    private Sensor PressureSensor;
    private float[] PressureValue = {0,0,0};
    private float[] orientationValue = {0,0,0};

    public static boolean isExpired = false;
    boolean isChange = false;

    public static float angle = 0;
    public static float GPSAngle = 0;
    public static int Pressure = 0;

    private LocationManager locationManager;
    private LocationListener locationListener;

    private TextView textViewSpeed;
    private TextView textViewAltitude;
    private TextView textViewBearing;
    private TextView textViewAccuracy;
    private TextView textViewDate;
    private TextView textViewTime;

    private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    private SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm:ss");


    private TextView textViewAngle;

    private CompassView compassView;
    private Location location;
    private AdView adView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //************广告开始************//
        // 创建adView。
        adView = new AdView(this);
        adView.setAdUnitId("ca-app-pub-6427167969550621/7563710590");
        adView.setAdSize(AdSize.BANNER);

//        320x50	标准横幅广告	手机和平板电脑	BANNER
//        320x100	大横幅	手机和平板电脑	LARGE_BANNER
//        300x250	IAB中矩形	手机和平板电脑	MEDIUM_RECTANGLE
//        468x60	IAB全尺寸横幅广告	平板电脑	FULL_BANNER
//        728x90	IAB页首横幅广告	平板电脑	LEADERBOARD
//        查看表格	智能横幅广告	手机和平板电脑	SMART_BANNER

        // 查询LinearLayout，假设其已指定
        // 属性android:id="@+id/mainLayout"。
        LinearLayout layout = (LinearLayout)findViewById(R.id.adMob);

        // 在其中添加adView。
        layout.addView(adView);

//        Bundle bundle = new Bundle();
//        bundle.putString("color_bg", "AAAAFF");//背景颜色
//        bundle.putString("color_bg_top", "FFFFFF");//顶部的渐变背景色
//        bundle.putString("color_border", "FFFFFF");//边框颜色
//        bundle.putString("color_link", "000080");//链接文字颜色
//        bundle.putString("color_text", "808080");//文字颜色
//        bundle.putString("color_url", "008000");//网址颜色

//        AdMobExtras extras = new AdMobExtras(bundle);

        // 启动一般性请求。
        AdRequest adRequest = new AdRequest.Builder()
                .addTestDevice(AdRequest.DEVICE_ID_EMULATOR)          // 模拟器
                .addTestDevice("A03EE007D61ACD6F477499B09E1CF201") // 我的Galaxy Nexus测试手机
//                .addNetworkExtras(extras)//设置主题
                .build();

        // 在adView中加载广告请求。
        adView.loadAd(adRequest);
        //************广告结束************//

        compassView = (CompassView) findViewById(R.id.surfaceView);

        textViewAngle = (TextView) findViewById(R.id.textViewAngle);//角度值

        textViewSpeed = (TextView) findViewById(R.id.textViewSpeed);
        textViewAltitude = (TextView) findViewById(R.id.textViewAltitude);
        textViewBearing = (TextView) findViewById(R.id.textViewBearing);
        textViewAccuracy = (TextView) findViewById(R.id.textViewAccuracy);
        textViewDate = (TextView) findViewById(R.id.textViewDate);
        textViewTime = (TextView) findViewById(R.id.textViewTime);

        cSensorManager = (SensorManager) getSystemService(this.SENSOR_SERVICE);
        locationManager = (LocationManager) getSystemService(this.LOCATION_SERVICE);

        locationListener = new LocationListener() {
            @Override
            public void onLocationChanged(Location location1) {
                location = location1;
                updateGPSInfo();
            }
            @Override
            public void onStatusChanged(String s, int i, Bundle bundle) {

            }
            @Override
            public void onProviderEnabled(String s) {
                location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                updateGPSInfo();
            }
            @Override
            public void onProviderDisabled(String s) {
                location = null;
                updateGPSInfo();
            }
        };
    }


//    @Override
//    public boolean onCreateOptionsMenu(Menu menu) {
//        // Inflate the menu; this adds items to the action bar if it is present.
//        getMenuInflater().inflate(R.menu.menu_main, menu);
//        return true;
//    }
//
//    @Override
//    public boolean onOptionsItemSelected(MenuItem item) {
//        // Handle action bar item clicks here. The action bar will
//        // automatically handle clicks on the Home/Up button, so long
//        // as you specify a parent activity in AndroidManifest.xml.
//        int id = item.getItemId();
//
//        //noinspection SimplifiableIfStatement
//        if (id == R.id.action_settings) {
//            return true;
//        }
//
//        return super.onOptionsItemSelected(item);
//    }

    public void registerSensor(){
        orientationSensor = cSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION);
        PressureSensor = cSensorManager.getDefaultSensor(Sensor.TYPE_PRESSURE);
        boolean ok = cSensorManager.registerListener(this, orientationSensor,SensorManager.SENSOR_DELAY_UI);
        boolean ok1 = cSensorManager.registerListener(this, PressureSensor,SensorManager.SENSOR_DELAY_UI);
//        accelerometerSensor = cSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
//        cSensorManager.registerListener(this, accelerometerSensor,SensorManager.SENSOR_DELAY_UI);
    }

    private void registerGPS(){
        location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        updateGPSInfo();
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,2000,5,locationListener);
    }

    protected void updateAngle(){
        textViewAngle.setText("" + (float)(Math.round(angle*10))/10);

        if(location != null && (System.currentTimeMillis() - location.getTime()) > 5000){
            if(!isExpired){
                isExpired = true;
                isChange = true;
            }
        }else {
            if(isExpired){
                isExpired = false;
                isChange = true;
            }
        }

        if(isChange){
            if(isExpired){
                textViewSpeed.setTextColor(Color.GRAY);
                textViewAltitude.setTextColor(Color.GRAY);
                textViewBearing.setTextColor(Color.GRAY);
                textViewAccuracy.setTextColor(Color.GRAY);
                textViewDate.setTextColor(Color.GRAY);
                textViewTime.setTextColor(Color.GRAY);
            }else {
                int i = getResources().getColor(android.R.color.holo_blue_dark);
                textViewSpeed.setTextColor(i);
                textViewAltitude.setTextColor(i);
                textViewBearing.setTextColor(i);
                textViewAccuracy.setTextColor(i);
                textViewDate.setTextColor(i);
                textViewTime.setTextColor(i);
            }
            isChange = false;
        }

    }

    protected void updateGPSInfo(){
        if(location == null){
            textViewSpeed.setText(R.string.textNull);
            textViewAltitude.setText(R.string.textNull);
            textViewBearing.setText(R.string.textNull);
            textViewAccuracy.setText(R.string.textNull);
            textViewDate.setText(R.string.textNull);
            textViewTime.setText(R.string.textNull);
        }else {
            textViewSpeed.setText("" + (float)(Math.round(location.getSpeed()*36))/10);
            textViewAltitude.setText("" + (float)(Math.round(location.getAltitude()*10))/10);
            textViewBearing.setText("" + (float)(Math.round(location.getBearing()*10))/10);
            textViewAccuracy.setText("" + (float)(Math.round(location.getAccuracy()*10))/10);
            textViewDate.setText("" + dateFormat.format(location.getTime()));
            textViewTime.setText("" + timeFormat.format(location.getTime()));
        }
    }

    @Override
    public void onSensorChanged(SensorEvent sensorEvent) {
        int i = sensorEvent.sensor.getType();
        if (i == Sensor.TYPE_ORIENTATION) {
            orientationValue = sensorEvent.values;
            angle = orientationValue[0];
//            if(this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE){
//                if(orientationValue[2] > 25){
//                    orientationAngle = 90;
//                }else if(orientationValue[2] < -25){
//                    orientationAngle = 270;
//                }
//            }else {
//                orientationAngle = 0;
//            }

//            angle = (orientationValue[0] + orientationAngle)%360;
            if(location != null){
                GPSAngle = location.getBearing();
            }else{
                GPSAngle = -1;
            }
            updateAngle();//更新角度\
            compassView.compassThread.run();//更新指针
        }else if(i == Sensor.TYPE_PRESSURE){
            PressureValue = sensorEvent.values;
            Pressure = (int)(PressureValue[0]*100);
        }
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int i) {

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
    @Override
    protected void onPause() {
        super.onPause();
        cSensorManager.unregisterListener(this);
        locationManager.removeUpdates(locationListener);
    }

    @Override
    protected void onResume() {
        super.onResume();
        registerSensor();
        registerGPS();
    }
}
